<template>
    <el-dialog :title="title" :visible.sync="visible" width="560px" append-to-body :close-on-click-modal="false">
        <BaseForm2
            ref="form"
            v-loading="loading"
            label-position="right"
            label-width="86px"
            :fields="fields"
            :text-model="textModel"
            :data="form"
            size="medium"
        ></BaseForm2>
        <div slot="footer" class="dialog-footer">
            <BaseButton :loading="submitLoading" @click="submitForm">保 存</BaseButton>
            <BaseButton type="recond" @click="cancel">取 消</BaseButton>
        </div>
    </el-dialog>
</template>

<script>
import BaseForm2 from '@/components/BaseForm2'
import { PriorityOrderingModel } from '@/models'
import { isNumber3 } from '@/utils/validate'
import BigNumber from 'bignumber.js'

// 必填且数字或者小数
const validIsNumberOrDecimals = (rule, value, callback) => {
    if (value === '' || value === undefined) {
        callback(new Error('必填项'))
    } else if (!isNumber3(value)) {
        callback(new Error('格式错误'))
    } else if (value < 0 || value > 1) {
        callback(new Error('只能输入0-1的小数'))
    } else {
        callback()
    }
}

export default {
    name: 'AddOrUpdate',
    components: {
        BaseForm2
    },
    data() {
        return {
            model: new PriorityOrderingModel(),
            title: '新增模型',
            visible: false,
            submitLoading: false,
            loading: false,
            // 表单参数
            form: {},
            type: 'add',
            id: '',
            textModel: false,
            fields: [
                {
                    label: '',
                    children: [
                        {
                            key: 'modelName',
                            type: 'input',
                            label: '模型名称',
                            maxlength: '30',
                            'show-word-limit': true,
                            span: 24,
                            rules: [
                                { required: true, message: '必填项', trigger: ['blur'] },
                                { validator: this.validUnique, trigger: ['blur'] }
                            ]
                        },
                        {
                            key: 'applyUnit',
                            type: 'input',
                            label: '应用单位',
                            maxlength: '50',
                            'show-word-limit': true,
                            span: 24,
                            rules: [{ required: true, message: '必填项', trigger: ['blur'] }]
                        },
                        {
                            key: 'ktechnologyGrade',
                            type: 'input',
                            labelSlot: 'K<sub>技术等级</sub>',
                            required: true,
                            placeholder: '请输入数字',
                            span: 24,
                            rules: [{ validator: validIsNumberOrDecimals, trigger: ['blur'] }]
                        },
                        {
                            key: 'ktraffic',
                            type: 'input',
                            labelSlot: 'K<sub>交通量</sub>',
                            required: true,
                            placeholder: '请输入数字',
                            span: 24,
                            rules: [{ validator: validIsNumberOrDecimals, trigger: ['blur'] }]
                        },
                        {
                            key: 'kpqi',
                            type: 'input',
                            labelSlot: 'K<sub>PQI</sub>',
                            required: true,
                            placeholder: '请输入数字',
                            span: 24,
                            rules: [{ validator: validIsNumberOrDecimals, trigger: ['blur'] }]
                        },
                        {
                            key: 'kadministrationGrade',
                            type: 'input',
                            labelSlot: 'K<sub>行政等级</sub>',
                            required: true,
                            placeholder: '请输入数字',
                            span: 24,
                            rules: [{ validator: validIsNumberOrDecimals, trigger: ['blur'] }]
                        },
                        {
                            key: 'kroadAge',
                            type: 'input',
                            labelSlot: 'K<sub>路龄</sub>',
                            required: true,
                            placeholder: '请输入数字',
                            span: 24,
                            rules: [{ validator: validIsNumberOrDecimals, trigger: ['blur'] }]
                        },
                        {
                            key: 'kpoliticsReason',
                            type: 'input',
                            labelSlot: 'K<sub>政治因素</sub>',
                            required: true,
                            placeholder: '请输入数字',
                            span: 24,
                            rules: [{ validator: validIsNumberOrDecimals, trigger: ['blur'] }]
                        }
                    ]
                }
            ]
        }
    },
    methods: {
        // 取消按钮
        cancel() {
            this.visible = false
            this.reset()
        },
        async open(options = {}) {
            const { type, id = null } = options
            this.id = id
            this.visible = true
            this.reset()
            if (type === 'add') {
                this.title = '新增模型'
            } else {
                this.title = '修改模型'
                this.form = await this.getDetail()
            }
        },
        // 表单重置
        reset() {
            this.$nextTick(() => {
                this.$refs['form'].resetFields()
            })
        },
        getDetail() {
            this.loading = true
            return this.model.detail({ id: this.id }).finally(() => {
                this.loading = false
            })
        },
        submitForm() {
            this.$refs['form'].validate((valid, res) => {
                if (valid) {
                    console.log(res)
                    this.submitLoading = true
                    // 计算6项指标和是否为1
                    if (
                        new BigNumber(res.kroadAge)
                            .plus(res.ktraffic)
                            .plus(res.kpqi)
                            .plus(res.kadministrationGrade)
                            .plus(res.ktechnologyGrade)
                            .plus(res.kpoliticsReason)
                            .toNumber() !== 1
                    ) {
                        this.$message.error('各项指标之和要为1')
                        this.submitLoading = false
                        return
                    }
                    this.id && (res.id = this.id)
                    this.model
                        .saveOrUpdate(res)
                        .then(() => {
                            this.$message({
                                type: 'success',
                                message: '操作成功！',
                                duration: 500,
                                onClose: () => {
                                    this.visible = false
                                    this.$emit('success')
                                }
                            })
                        })
                        .finally(() => {
                            this.submitLoading = false
                        })
                } else {
                    this.$message.error('校验失败！')
                }
            })
        },
        validUnique(rule, value, callback) {
            this.model.uniqueCheck({ modelName: value, id: this.id || null }).then((res) => {
                if (!res) {
                    callback(new Error('该名称已存在'))
                } else {
                    callback()
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.w-300 {
    width: 300px;
}
</style>
